package com.open.exam.businessservice;

import com.open.exam.common.CommonFunction;
import com.open.exam.common.ExamSitePath;
import com.open.exam.common.OperationResult;
import com.open.exam.common.TestPaperFromPackageGenerator;
import com.open.exam.databasemodel.*;
import com.open.exam.dto.*;
import com.open.exam.enums.*;
import com.open.exam.examinerbehavior.*;
import com.open.exam.examresult.AnswerRecord;
import com.open.exam.examresult.ExaminerBaseInfo;
import com.open.exam.examresult.ExaminerExamResult;
import com.open.exam.examresult.ExaminerPaperInfo;
import com.open.exam.itemmodel.ICreaterFactory;
import com.open.exam.itemmodel.IHtmlCreater;
import com.open.exam.mapper.*;
import com.open.exam.utils.DateUtil;
import com.open.exam.utils.FileUtil;
import com.open.exam.utils.GsonUtil;
import com.openexam.openqti.openqtipaperquestion.*;
import com.openexam.openqti.qti.AssessmentItem;
import com.openexam.openqti.qti.AssessmentTest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author 奶茶
 * Created by on 2017/12/8.
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class ExamReportBusinessService {

    private static final Logger logger = LoggerFactory.getLogger(ExamReportBusinessService.class.getName());

    @Autowired
    private ExamReportMapper examReportMapper;
    @Autowired
    private ExamingMoniterLogMapper examingMoniterLogMapper;
    @Autowired
    private ExamPlanInfoMapper examPlanInfoMapper;
    @Autowired
    private FreeExamReportMapper freeExamReportMapper;
    @Autowired
    private ExamineeAnswerDetailMapper examineeAnswerDetailMapper;
    @Autowired
    private ExamPaperItemMapper examPaperItemMapper;
    @Autowired
    private ExamPhotoMapper examPhotoMapper;
    @Autowired
    private ExamPaperMapper examPaperMapper;

    @Value("${PackageKEY}")
    private String packageKey;

    private static JAXBContext assessmentTestJAXBContext;
    private static JAXBContext assessmentItemJAXBContext;
    static {
        try {
            assessmentTestJAXBContext = JAXBContext.newInstance(AssessmentTest.class);
            assessmentItemJAXBContext = JAXBContext.newInstance(AssessmentItem.class);
        } catch (JAXBException e) {
            logger.error("JAXBException",e);
        }
    }

    /**
     * 根据考生列表创建监考报告
     * @param list
     * @param deployMode 部署方式
     * @return
     */
    public String createExamReport(List<ExamingMonitorViewModel> list,Integer deployMode){
        ExaminerBehavior examinerBehavior = new ExaminerBehavior();
        if(list != null && !list.isEmpty()){
            ExamingMonitorViewModel model = list.get(0);

            examinerBehavior.setExamPlanID(model.getExtendInfo().getExamplanID());
            examinerBehavior.setExamSceneID(model.getExamSceneID());
            examinerBehavior.setExamRoomID(model.getExamRoomID());
            examinerBehavior.setExamSiteID(model.getExamSiteID());
            examinerBehavior.setSubjectID(model.getExamSubjectID());

            StringBuilder builder = new StringBuilder(model.getExtendInfo().getExamplanID()).append("/").append(model.getExamSiteID()).append("/files/result/").append(model.getExamSubjectCode()).append("/AssessmentResults/ASR_");
            for (ExamingMonitorViewModel item:list) {
                Examiner examiner = new Examiner();
                //考生编号
                examiner.setExamineeID(item.getExamineeID());
                //登陆时间
                examiner.setLoginTime(item.getLoginTime());
                //考试结果文件
                if(item.getExamineeResult() == null || ("").equals(item.getExamineeResult())){
                    examiner.setResultFilePath("");
                }else{
                    examiner.setResultFilePath(builder.toString() + item.getExamineeID() + "_" +item.getExamPaperID().toUpperCase() + ".json");
                }
                //考生重考序号
                examiner.setRetryIndex(0);
                //考试科目编号
                examiner.setSubjectID(item.getExamSubjectID());
                //是否缺考
                examiner.setAbsence(item.getSysState() != 3);
                examiner.setSignInStatus(item.getRegister());
                examiner.setSignInTime(item.getRegisterTime());
                examiner.setSignInRemark(item.getRemark());

                //监考报告增加学生列表
                examinerBehavior.getExaminers().add(examiner);
                //强制交卷
                if(item.getSubmitType().equals(TestPaperSubmitType.CompellentSubmit.getPrefix())){

                    EnforceSubmitPaperRecord record = new EnforceSubmitPaperRecord();
                    record.setComment("");
                    record.setOperationTime(item.getExamEndTime());
                    record.setExaminerID(item.getExamineeID());
                    examinerBehavior.getEnforceSubmitPaperRecords().add(record);
                }

                for (Behavior c:item.getBehavior()) {
                    Integer typeID = c.getTypeID();
                    Object behaviorByType = CommonFunction.getBehaviorByType(typeID, item.getExamineeID(), c.getMemo(), c.getReason(), c.getLogTime(), item.getDelayedTime(), item.getRelBeginTime());
                    switch (typeID){
                        //延时
                        case 1:
                            examinerBehavior.getDelayRecords().add((DelayRecord) behaviorByType);
                            break;
                        //换机
                        case 2:
                            examinerBehavior.getChangeSeatRecords().add((ChangeSeatRecord)behaviorByType);
                            break;
                        //强制交卷
                        case 3:
                            break;
                        //作弊 //调整时间
                        case 4:
                        case 5:
                            examinerBehavior.getViolateRuleRecords().add((ViolateRuleRecord) behaviorByType);
                            break;
                        //整场重考
                        case 6:
                            examinerBehavior.getAccidentsProcessRecords().add((AccidentsProcessRecord) behaviorByType);
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        return GsonUtil.toJson(examinerBehavior);
    }


    /**
     * 随考监考详情页面
     * @param appId
     * @param planId
     * @param subjectId
     * @param siteId
     * @param examCardNo
     * @param examineeName
     * @return
     */
    public List<ExamingMonitorViewModel> findFreeExamReportList(String appId, String planId, String subjectId, String siteId, String examCardNo, String examineeName){
        List<ExamingMonitorViewModel> retList = new ArrayList<>();

        List<Map<String, Object>> freeExamReportList = examReportMapper.findFreeExamReportList(appId, planId, subjectId, siteId,examCardNo,examineeName);
        for (Map<String, Object> map:freeExamReportList){
            ExamingMonitorViewModel model = new ExamingMonitorViewModel();
            model.setId(map.get("ID").toString());
            model.setExamCardNo((String) map.get("ExamCardNo"));
            model.setSysState((Integer) map.get("SysState"));
            model.setExamineeName((String) map.get("ExamineeName"));
            model.setExamEndTime(DateUtil.convertMillisecondToDateString(DateUtil.convertStringToDate(map.get("ExamEndTime").toString()).getTime() + ((Integer)map.get("DelayMinute"))*60*1000));
            model.setExamSubjectName((String)map.get("SubjectName"));
            model.setExamSubjectID((String) map.get("ExamSubjectID"));
            model.setExamSceneID((String) map.get("ExamSceneID"));
            model.setExamRoomID((String) map.get("ExamRoomID"));
            model.setExamineeID((String) map.get("ExamineeID"));
            model.setAccountType((Integer)map.get("AccountType"));

            List<ExamingMonitorLog> logs = examingMoniterLogMapper.findListByArrangeId(map.get("ID").toString());
            List<Behavior> behaviors = new ArrayList<>();

            for (ExamingMonitorLog log:logs) {
                Behavior behavior = new Behavior();
                behavior.setMemo(log.getMemo());
                behavior.setReason(log.getReason());
                behavior.setTypeID(log.getTypeID());
                behaviors.add(behavior);
            }
            model.setBehavior(behaviors);
            retList.add(model);
        }

        return retList;
    }

    /**
     * 保存随考监考报告信息
     * @param appId
     * @param siteId
     * @param planId
     * @param infoList
     * @return
     */
    public OperationResult freeExamInfo(String appId, String siteId, String planId, List<FreeExamExamineeInfo> infoList,AdminInfo adminInfo) throws Exception {
        //按场次分组
        Map<String, List<FreeExamExamineeInfo>> listMap = infoList.stream().collect(Collectors.groupingBy(FreeExamExamineeInfo::getSceneId));
        for (Map.Entry<String, List<FreeExamExamineeInfo>> sceneGroup:listMap.entrySet()){
            //按照考场分组
            Map<String, List<FreeExamExamineeInfo>> listMap1 = sceneGroup.getValue().stream().collect(Collectors.groupingBy(FreeExamExamineeInfo::getRoomId));
            for (Map.Entry<String, List<FreeExamExamineeInfo>> roomGroup:listMap1.entrySet()) {
                //再按科目分组
                Map<String, List<FreeExamExamineeInfo>> listMap2 = roomGroup.getValue().stream().collect(Collectors.groupingBy(FreeExamExamineeInfo::getSubjectId));
                for (Map.Entry<String, List<FreeExamExamineeInfo>> subjectGroup:listMap2.entrySet()) {
                    List<ExamingMonitorViewModel> examineeList = new ArrayList<>();
                    for (FreeExamExamineeInfo examineeInfo:subjectGroup.getValue()) {
                        //获取监考列表
                        List<ExamingMonitorViewModel> list = examReportMapper.findFreeExamingMoniterList(appId, subjectGroup.getKey(), planId, ExamManagerState.Submited.getPrefix(), examineeInfo.getExamineeId());

                        //将信息写入随考监考信息表
                        FreeExamReport freeExamReport = freeExamReportMapper.getFreeExamReportByWhere(appId, planId, subjectGroup.getKey(), roomGroup.getKey());
                        if(freeExamReport == null && !list.isEmpty()){
                            freeExamReport = new FreeExamReport();
                            freeExamReport.setAppID(appId);
                            freeExamReport.setExamPlanInfoID(planId);
                            freeExamReport.setExamSubjectID(subjectGroup.getKey());
                            // 借用ExamReport存储考场标识
                            freeExamReport.setExamReport(roomGroup.getKey());
                            freeExamReport.setExamResult("");
                            freeExamReport.setIfUpload(ExamResultUploadState.DontUpload.getPrefix().shortValue());

                            freeExamReportMapper.insertFreeExamReport(freeExamReport);
                        }

                        //获取日志内容的信息
                        for (ExamingMonitorViewModel item:list) {
                            item.setExamEndTime(DateUtil.convertMillisecondToDateString(DateUtil.convertStringToDate(item.getExamEndTime()).getTime() + item.getDelayMinute()*60*1000));
                            List<ExamingMonitorLog> logs = examingMoniterLogMapper.findListByArrangeId(item.getId());
                            List<Behavior> behaviors = new ArrayList<>();
                            for (ExamingMonitorLog log:logs) {
                                Behavior behavior = new Behavior();
                                behavior.setMemo(log.getMemo());
                                behavior.setTypeID(log.getTypeID());
                                behavior.setReason(log.getReason());
                                behaviors.add(behavior);
                            }
                            item.setBehavior(behaviors);

                            ExtendInfo extendInfo = new ExtendInfo();
                            extendInfo.setAppID(appId);
                            extendInfo.setAppName(adminInfo.getAppName());
                            extendInfo.setExamSiteID(adminInfo.getExamSiteID());
                            extendInfo.setExamSiteName(adminInfo.getExamSiteName());
                            extendInfo.setExamplanID(planId);
                            extendInfo.setExamPlanName(examPlanInfoMapper.findExamPlanInfoFirst(planId).getExamPlanName());

                            item.setExtendInfo(extendInfo);
                            examineeList.add(item);
                        }
                    }

                    if(!examineeList.isEmpty()){
                        //获取当前计划的部署方式
                        String examreport = packageReportWAN(appId,siteId,planId,sceneGroup.getKey(),roomGroup.getKey(),subjectGroup.getKey(),examineeList);
                        if(examreport == null){
                            return new OperationResult(OperationResultType.Error, "打包未成功");
                        }else{
                            //找到要保存的监考报告
                            FreeExamReport freeExamReport = freeExamReportMapper.getFreeExamReportByWhere(appId, planId, subjectGroup.getKey(), roomGroup.getKey());
                            //更新监考报告内容
                            freeExamReport.setExamResult(examreport);
                            freeExamReport.setIfUpload(ExamResultUploadState.AutoUpload.getPrefix().shortValue());
                            freeExamReportMapper.updateIncludeInfo(freeExamReport);
                            return new OperationResult(OperationResultType.Success,freeExamReport);
                        }
                    }else{
                        return new OperationResult(OperationResultType.Error, "没有可打包的考生");
                    }
                }
            }
        }
        return new OperationResult(OperationResultType.Error, "没有可打包的考生");
    }

    /**
     * 针对网考打包_不压缩_只返回结果文件地址_重复文件先删除后覆盖
     * @param appId
     * @param siteId
     * @param planId
     * @param sceneId
     * @param roomId
     * @param subjectId
     * @param examingMonitorViewModelList
     * @return
     * @throws Exception
     */
    private String packageReportWAN(String appId,String siteId,String planId,String sceneId,String roomId,String subjectId,List<ExamingMonitorViewModel> examingMonitorViewModelList) throws Exception {

        //获取当前计划的部署方式
        ExamingMonitorViewModel monitorViewModel = examingMonitorViewModelList.get(0);
        Integer deploymentMode = monitorViewModel.getDeploymentMode();

        //结果文件基础路径
        StringBuilder resultBasePathAppender = new StringBuilder(ExamSitePath.rootPath).append("/").append(planId).append("/").append(siteId).append("/files/result/").append(monitorViewModel.getExamSubjectCode()).append("/");
        //考生结果文件存放路径
        String examResultFilePath = resultBasePathAppender + "AssessmentResults/";

        //查询所有试卷
        Map<String, String> allExamPaper = getAllExamPaper(planId, subjectId);

        //作答结果文件名称
        for (ExamingMonitorViewModel examinee:examingMonitorViewModelList) {
            //合成新的整卷作答结果：作答、判分
            //只操作已交卷的考生
            if(examinee.getSysState() == 3){
                //考生当前全部作答
                List<ExamineeAnswerDetailViewModel> examineeAnswerDetailViewModels = new ArrayList<>();
                List<Map<String, Object>> examineeAnswerDetails = examineeAnswerDetailMapper.findExamineeAnswerDetails(examinee.getExamineeID(), examinee.getExamPaperID().toLowerCase());
                for (Map<String, Object> map:examineeAnswerDetails){
                    ExamineeAnswerDetailViewModel examineeAnswerDetailViewModel = new ExamineeAnswerDetailViewModel();
                    examineeAnswerDetailViewModel.setExamPaperID((String) map.get("ExamPaperID"));
                    examineeAnswerDetailViewModel.setExamPaperItemId((String)map.get("ExamPaperItemId"));
                    examineeAnswerDetailViewModel.setSequenceIndex((Integer)map.get("SequenceIndex"));
                    examineeAnswerDetailViewModel.setIsCompletion((Integer)map.get("IsCompletion"));
                    examineeAnswerDetailViewModel.setAnswerResults(GsonUtil.fromJsonToList((String) map.get("AnswerResults"),String.class));
                    examineeAnswerDetailViewModel.setMarked(Boolean.valueOf(map.get("IsMarked").toString()));
                    examineeAnswerDetailViewModels.add(examineeAnswerDetailViewModel);
                }

                //实例化 QTI 模型
                OpenAssessmentTest openAssessmentTest = new OpenAssessmentTest();
                openAssessmentTest.LoadFromString(allExamPaper.get(examinee.getExamPaperID()),assessmentTestJAXBContext);

                //获取试题集合
                List<ExamineeExamPaperItem> examPaperItems = examPaperItemMapper.findExamineePaperItemByExamPaperInfoId(examinee.getExamPaperID());
                Map<String,String> dic = new HashMap<>(50);
                for (ExamineeExamPaperItem paperItem:examPaperItems) {
                    if(!dic.containsKey(paperItem.getItemID())){
                        dic.put(paperItem.getItemID().toLowerCase(),paperItem.getItemContent());
                    }
                }

                //实例化 QTI 结果模型
                OpenAssessmentResult openAssessmentResult = TestPaperFromPackageGenerator.getOpenItemResultCollection(openAssessmentTest, dic,assessmentItemJAXBContext);

                //考生基础信息
                ExaminerBaseInfo examinerBaseInfo = new ExaminerBaseInfo();
                examinerBaseInfo.setExaminerID(examinee.getExamineeID());
                examinerBaseInfo.setExaminerName(examinee.getExamineeName());
                examinerBaseInfo.setExamCardNo(examinee.getExamCardNo());
                examinerBaseInfo.setExamPlanID(examinee.getExtendInfo().getExamplanID());
                examinerBaseInfo.setExamPlanName(examinee.getExtendInfo().getExamPlanName());
                examinerBaseInfo.setExamRoomID(examinee.getExamRoomID());
                examinerBaseInfo.setExamRoomName(examinee.getExamRoomName());
                examinerBaseInfo.setExamSceneID(examinee.getExamSceneID());
                examinerBaseInfo.setExamSceneName(examinee.getExamSceneName());
                examinerBaseInfo.setExamSiteID(examinee.getExamSiteID());
                examinerBaseInfo.setExamSiteName(examinee.getExamSiteName());
                examinerBaseInfo.setExamSubjectID(examinee.getExamSubjectID());
                examinerBaseInfo.setExamSubjectName(examinee.getExamSubjectName());
                //获取考生照片
                examinerBaseInfo.setScenePhotos(examPhotoMapper.findExamPhotoListByExaminerArrangeID(examinee.getId()));


                //考生作答集合
                List<AnswerRecord> answerRecords = new ArrayList<>();
                //获取试卷
                TestPaperTemplate testPaper = getStudentPaper(openAssessmentTest, examPaperItems, examinee.getSourceExamPaperID());

                //合成新的 QTI 结果模型
                openAssessmentResult.getItemResultCollection().clear();
                for (SectionTemplate section:testPaper.getSectionTemplateCollection()) {
                    for (ItemTemplate item:section.getItemTemplateCollection()) {
                        //获取当前试题作答
                        ExamineeAnswerDetailViewModel answer = null;
                        if(!examineeAnswerDetailViewModels.isEmpty()){
                            List<ExamineeAnswerDetailViewModel> collect = examineeAnswerDetailViewModels.stream()
                                    .filter(e -> e.getExamPaperID().equalsIgnoreCase(examinee.getExamPaperID()))
                                    .filter(e -> e.getExamPaperItemId().equalsIgnoreCase(item.getIdentifier()))
                                    .collect(Collectors.toList());
                            if(collect != null && !collect.isEmpty()){
                                answer = collect.get(0);
                            }
                        }
                        if(answer != null){
                            item.setSequenceIndex(answer.getSequenceIndex());
                            item.setItemCompletionStatus(answer.getIsCompletion());
                            item.setMarked(answer.getMarked());
                            item.setCandidateResponses(answer.getAnswerResults() == null || answer.getAnswerResults().isEmpty() ? item.getCorrectResponses().stream().map(s -> "").collect(Collectors.toList()) : answer.getAnswerResults());
                        }else{
                            //作答为null 将考生作答设置为和正确作答集合大小相同 value为 "" 的集合
                            item.setCandidateResponses(item.getCorrectResponses().stream().map(s -> "").collect(Collectors.toList()));
                        }

                        if(item.getSubjective() && item.getAssessmentItemType() == 6 && isSubjective(item)){
                            List<String> candidate = new ArrayList<>();
                            candidate.add(" ");
                            item.setCandidateResponses(candidate);
                        }

                        //考生作答结果
                        AnswerRecord answerRecord = new AnswerRecord();
                        answerRecord.setQuestionID(item.getIdentifier());
                        answerRecord.setAnswer(item.getCandidateResponses());
                        answerRecord.setCompletionStatus(item.getItemCompletionStatus());
                        answerRecord.setSubjective(CommonFunction.isSubjective(item.getAssessmentItemType()));

                        IHtmlCreater creater = ICreaterFactory.getInstance(item);
                        OpenItemResult save = creater.save(item);
                        openAssessmentResult.getItemResultCollection().add(save);
                        for (OpenScoreOutcomeVariable scoreOutcomeVariable: save.getScoreOutcomeVariables()) {
                            if("SCORE".equals(scoreOutcomeVariable.getIdentifier())){
                                answerRecord.setScore(scoreOutcomeVariable.getCandidateScore());
                                break;
                            }
                        }
                        answerRecords.add(answerRecord);
                    }
                }

                //总分
                double score = 0;
                for (OpenItemResult itemResult:openAssessmentResult.getItemResultCollection()) {
                    for (OpenScoreOutcomeVariable openScoreOutcomeVariable:itemResult.getScoreOutcomeVariables()) {
                        if("SCORE".equals(openScoreOutcomeVariable.getIdentifier())){
                            score += openScoreOutcomeVariable.getCandidateScore();
                        }
                    }
                }

                //考生试卷结果
                ExaminerPaperInfo examinerPaperInfo = new ExaminerPaperInfo();
                examinerPaperInfo.setPaperID(testPaper.getIdentifier());
                examinerPaperInfo.setObjectiveScore(score);

                //考生作答
                ExaminerExamResult examinerExamResult = new ExaminerExamResult();
                examinerExamResult.setExaminerBaseInfo(examinerBaseInfo);
                examinerExamResult.setAnswerRecords(answerRecords);
                examinerExamResult.setExaminerPaperInfo(examinerPaperInfo);

                //获取结果XML
                if(examinerExamResult.getAnswerRecords() != null && examinerExamResult.getExaminerBaseInfo() != null && examinerExamResult.getExaminerPaperInfo()!= null){
                    //生成结果json文件
                    FileUtil.writeStrToFile2(examResultFilePath,String.format("ASR_%s_%s.json",examinee.getExamineeID(),examinee.getExamPaperID().toUpperCase()),GsonUtil.toJson(examinerExamResult));
                    examinee.setExamineeResult(examResultFilePath + String.format("ASR_%s_%s.json",examinee.getExamineeID(),examinee.getExamPaperID().toUpperCase()));
                }
            }
        }


        //考试结果详情json文件
        String examReportJson = CommonFunction.replaceNS2(createExamReport(examingMonitorViewModelList,deploymentMode));
        String fileName = String.format("%s_%s_%s.json",sceneId,roomId,System.currentTimeMillis());
        FileUtil.writeStrToFile(resultBasePathAppender.toString(),fileName,examReportJson);

        return resultBasePathAppender + fileName;
    }

    public Boolean isSubjective(ItemTemplate item){
        return item.getCandidateResponses() == null || item.getCandidateResponses().isEmpty();
    }

    /**
     * 获取所有试卷
     * @param examPlanID
     * @param examSubjectID
     * @return
     */
    private Map<String,String> getAllExamPaper(String examPlanID,String examSubjectID){
        //查询所有试卷
        Map<String,String> allExamPaper = new HashMap<>();
        List<ExamPaper> examPaperList = examPaperMapper.finaAllExamPaper(examPlanID, examSubjectID);
        examPaperList.parallelStream().forEach(
                examPaper -> allExamPaper.put(examPaper.getExamPaperID(),examPaper.getExamPaperContent())
        );
        return allExamPaper;
    }

    /**
     * 获取考生试卷
     * @param openAssessmentTest
     * @param examPaperItems
     * @param examineeExamPaperID
     * @return
     */
    private TestPaperTemplate getStudentPaper(OpenAssessmentTest openAssessmentTest, List<ExamineeExamPaperItem> examPaperItems, String examineeExamPaperID) throws Exception {
        TestPaperTemplate testPaper = new TestPaperTemplate();

        Integer itemCount = 0;
        Double score = 0.0;
        Integer i = 0;

        for (OpenTestPart testPart:openAssessmentTest.getTestPartCollection()) {
            for (OpenAssessmentSection section:testPart.getAssessmentSectionCollection()) {
                score += section.getScore();
                itemCount += section.getItemCount();

                SectionTemplate sectionTemplate = new SectionTemplate();
                sectionTemplate.setScore(score);
                sectionTemplate.setIdentifier(section.getIdentifier());
                sectionTemplate.setItemCount(section.getItemCount());
                sectionTemplate.setTitle(section.getTitle());
                sectionTemplate.setItemIndex(testPaper.getSectionTemplateCollection().size()+1);

                for (OpenAssessmentItemRef itemRef:section.getAssessmentItemRefCollection()) {
                    OpenAssessmentItem questionModel = OpenAssessmentItem.createInstance(itemRef.getType());
                    String itemContent = examPaperItems.stream().filter(s -> s.getItemID().toLowerCase().equals(itemRef.getIdentifier().toLowerCase())).collect(Collectors.toList()).get(0).getItemContent();
                    questionModel.LoadFromString(itemContent,assessmentItemJAXBContext);

                    ItemTemplate temp = ICreaterFactory.getItemObject(questionModel);
                    temp.setAssessmentItemType(itemRef.getType().getIndex());
                    temp.setIdentifier(itemRef.getIdentifier());
                    temp.setExample(itemRef.isExample());
                    temp.setMedia(itemRef.getMedia());
                    temp.setSubjective(itemRef.isSubjective());
                    temp.setTitle(questionModel.getTitle());
                    temp.setWeight(itemRef.getWeight());
                    temp.setResponseDuration(itemRef.getResponseDuration());
                    temp.setQuestionAnalysis("");
                    temp.setPromptShowDuration(itemRef.getPromptShowDuration());
                    temp.setScore(itemRef.getWeight());
                    temp.setItemIndex(sectionTemplate.getItemTemplateCollection().size()+1);
                    temp.setSequenceIndex(++i);
                    temp.setCorrectResponses(ICreaterFactory.getItemResult(questionModel));

                    sectionTemplate.getItemTemplateCollection().add(temp);

                }
                testPaper.getSectionTemplateCollection().add(sectionTemplate);
            }
        }
        testPaper.setIdentifier(examineeExamPaperID);
        testPaper.setTitle(openAssessmentTest.getTitle());
        testPaper.setItemCount(itemCount);
        testPaper.setScore(score);

        return testPaper;
    }

}
